# views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required, user_passes_test
from django.urls import reverse
from .models import User
from .forms import UserForm

from django.contrib.auth import authenticate, login, logout
from django.contrib import messages



def is_admin(user):
    return user.is_authenticated and user.is_admin()


def user_list(request):
    users = User.objects.all().order_by('-createTime')
    return render(request, 'manager/user_list.html', {'users': users})


def user_add(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('user_list')
    else:
        form = UserForm()
    return render(request, 'manager/user_form.html', {'form': form, 'title': '添加用户'})


def user_edit(request, pk):
    user = get_object_or_404(User, pk=pk)
    if request.method == 'POST':
        form = UserForm(request.POST, instance=user)
        if form.is_valid():
            form.save()
            return redirect('user_list')
    else:
        form = UserForm(instance=user)
    return render(request, 'manager/user_form.html', {'form': form, 'title': '编辑用户'})


def user_delete(request, pk):
    user = get_object_or_404(User, pk=pk)
    user.delete()
    return redirect('user_list')

